/*
 * @Author: 清羽
 * @Date: 2022-08-21 22:11:24
 * @LastEditTime: 2022-10-28 21:42:01
 * @LastEditors: you name
 * @Description: 用户store
 */
import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: ''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USER_ID: (state, userId) => {
    state.userId = userId
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  }
}

const actions = {
  // user login
  login ({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ phone: username.trim(), password: password }).then(response => {
        const { data } = response
        const token = data.data.token
        console.log("login => token", token)
        // data.token
        commit('SET_TOKEN', token)
        // commit('SET_USER_ID', data.session.user_id)
        setToken(token)
        // console.log("到这了")
        // this.$router.push({ path: '/' })
        // console.log("可能跳转了")
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo ({ commit, state }) {
    console.log("正在获取用户信息");
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response
        console.log("getInfo => response", response.data.data)

        if (!data) {
          return reject('Verification failed, please Login again.')
        }

        if (data.data.business) {
          commit('SET_AVATAR', '商家')
        }
        commit('SET_NAME', response.data.data.nickname)

        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout ({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken ({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

